package cn.iocoder.yudao.framework.common.util.collection;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collector;
import java.util.stream.Collectors;

/**
 * 集合封装类
 *
 * @author TangShuHan
 * @date 2022/7/11 16:52
 */
public class CollectKit {

    public static <T> List<T> filter(List<T> list, Predicate<? super T> predicate) {
        return list.stream().filter(predicate).collect(Collectors.toList());
    }

    public static <T, R> List<R> map(List<T> list, Function<? super T, ? extends R> mapper) {
        return list.stream().map(mapper).collect(Collectors.toList());
    }

    public static <T, R> List<R> fmap(List<T> list, Predicate<? super T> predicate, Function<? super T, ? extends R> mapper) {
        return list.stream().filter(predicate).map(mapper).collect(Collectors.toList());
    }

    public static <T> T find(List<T> list, Predicate<? super T> predicate, T orElse) {
        return list.stream().filter(predicate).findFirst().orElse(orElse);
    }

    public static <T, K, U> Map<K, U> toMap(List<T> list, Function<? super T, ? extends K> keyMapper,
                                            Function<? super T, ? extends U> valueMapper) {
        return list.stream().collect(Collectors.toMap(keyMapper, valueMapper));
    }

    public static <T, K> Map<K, List<T>> groupBy(List<T> list, Function<? super T, ? extends K> classifier) {
        return list.stream().collect(Collectors.groupingBy(classifier));
    }

    public static <T, K, A, D> Map<K, D> reckon(List<T> list, Function<? super T, ? extends K> classifier, Collector<? super T, A, D> downstream) {
        return list.stream().collect(Collectors.groupingBy(classifier, downstream));
    }

    public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
        Map<Object, Boolean> seen = new ConcurrentHashMap<>();
        return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
    }

    private CollectKit() {
    }
}
